package test.ssl;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.TrustManagerFactory;

public class Server extends Thread
{
	public static final int BIND_PORT = 8443;
	private Socket socket;

	public static void main(String[] args)
		throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
			IOException, UnrecoverableKeyException, KeyManagementException
	{
		//	构建证书文件流
		String path = Server.class.getResource("").getPath() + "Server.jks.pk";
		InputStream fis = new FileInputStream(path);
		String tpath = Server.class.getResource("").getPath() + "Server.jks.tk";
		InputStream tfis = new FileInputStream(tpath);

		//	构建证书存储信息对象
		KeyStore ks = KeyStore.getInstance("JKS");
		ks.load(fis, "123456".toCharArray());
		KeyStore tks = KeyStore.getInstance("JKS");
		tks.load(tfis, "123456".toCharArray());

		//	构建证书管理器工厂对象
		KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
		kmf.init(ks, "123456".toCharArray());

		//	构建受信证书管理器工厂对象
		TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
		tmf.init(tks);

		//	构建SSL上下文
		SSLContext ctx = SSLContext.getInstance("TLS");
		ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

		//	构建SSL套接字，绑定在特定端口，并接受连接
		SSLServerSocketFactory sf = ctx.getServerSocketFactory();
		ServerSocket ss = sf.createServerSocket(BIND_PORT);
		Socket socket = ss.accept();

		//	创建处理线程
		Server server = new Server();
		server.socket = socket;
		server.start();
	}

	public void run()
	{
		//	产生echo效果
		try
		{
			InputStream is = socket.getInputStream();
			InputStreamReader isr = new InputStreamReader(is, "UTF-8");
			BufferedReader br = new BufferedReader(isr);
			OutputStream os = socket.getOutputStream();
			PrintWriter pw = new PrintWriter(os, true);
			while(! socket.isClosed())
			{
				String s = br.readLine();
				if(s != null)
				{
					System.err.println(s);
					pw.println(s);
					pw.flush();
				}
				Thread.sleep(100);
			}
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		catch(InterruptedException e)
		{
			e.printStackTrace();
		}
	}
}
